#pragma once
#include <iostream>
#include <strings.h>
#include <cstring>
#include <string>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "Comm.hpp"
#include "Log.hpp"
#include "lnetAddr.hpp"

static const std::string defaultip = "0.0.0.0";
static const uint16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;



/// 有ip版本


class UdpServer:public nocopy
{
public:
     UdpServer(const std::string &ip = defaultip, uint16_t port = defaultport)
     :_ip(ip), _port(port)
     {}

     void Init()
     {
          //1.创建socket, 就是创建了文件细节
          _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
          if(_sockfd < 0)
          {
               lg.LogMessage(Fatal, "socket errr, %d : %s\n", errno, strerror(errno));
               exit(Socket_Err);
          }

          lg.LogMessage(Info, "socket success, sockfd: %d\n", _sockfd);

          //2.绑定，指定网络信息
          struct sockaddr_in local;
          bzero(&local, sizeof(local));//memset指定大小全部清零//头文件strings.h
          local.sin_family = AF_INET;
          local.sin_port = htons(_port);//htons是主机转网络

          local.sin_addr.s_addr = INADDR_ANY;//0,ip地址设为零  本地任意ip绑定的方式
          //local.sin_addr.s_addr = inet_addr(_ip.c_str());//1.将字符串风格的地址变4字节 2.变成网络序列
          
          //结构体填完，并未设置到内核中，还在栈中


          int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
          if(n != 0)
          {
               lg.LogMessage(Fatal, "bind errr, %d : %s\n", errno, strerror(errno));
               exit(Bind_Err);
          }

     }

     void Start()
     {
          //服务器永远不退出
          char buffer[defaultsize];
          for(;;)
          {
               struct sockaddr_in peer;
               socklen_t len = sizeof(peer);
               ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr *)&peer, &len);
               if(n > 0)
               {
                    
                    InetAddr addr(peer);
                    buffer[n] = 0;
                    std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
                    sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);

                    // buffer[n] = 0;
                    // std::cout << "client say# " << buffer << std::endl;
                    // //向客户端发送
                    // sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
               }
          }
          


     }

     ~UdpServer(){}

private:
     std::string _ip;//后面需要调整//动态绑定后不需要该ip地址
     uint16_t _port;
     int _sockfd;

};